package net.orange.architecture.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.orange.framework.model.User;

/**
 * Web Filter, every web request will go into it first, it can do the character
 * encoding and login checking here.
 */
public class WebFilter extends HttpServlet implements Filter {

	private static final long serialVersionUID = 1813780639244835236L;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig arg0) throws ServletException {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		FilterChain chain = arg2;

		request.setCharacterEncoding(Web.CHARACTER_ENCODING);

		// If access the views page, it need to log in first.
		String views = request.getContextPath() + Web.JSF_VIEWS_DIR;
		String requestURI = request.getRequestURI();
		User currentUser = (User) request.getSession().getAttribute(
				Web.JSF_USER_CURRENT);

		if (requestURI.startsWith(views) && currentUser == null) {
			response.sendRedirect(request.getContextPath() + "/mgr/relogin.jsf");
			return;
		}

		chain.doFilter(request, response);
	}
}
